<template>
  <div class="users">
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>
        <a href="/hello">首页</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- users主要内容 -->
    <el-card>
      <!-- 用户搜索 用户新增 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="queryInfo.query"
            @keydown.enter="getUserList"
            clearable
            @clear="getUserList"
            placeholder="请输入内容"
          >
            <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=!dialogVisible">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userList" border>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="ChangeSwitch(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <!-- 编辑数据 -->
            <el-button
              type="primary"
              @click="editChangeVal(scope.row.id)"
              size="mini"
              icon="el-icon-edit"
            ></el-button>
            <el-button
              type="danger"
              @click="removeInfo(scope.row.id)"
              size="mini"
              icon="el-icon-delete"
            ></el-button>
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
              <el-button
                type="warning"
                @click="SetUserRights(scope.row)"
                size="mini"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totol"
      ></el-pagination>
    </el-card>

    <!-- 新增用户 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="40%">
      <!-- 顶部from -->
      <!-- <span>这是一段信息</span> -->
      <el-form :rules="addUserFormRules" ref="addUserForm" :model="addUserForm" label-width="80px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="用户邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部确认 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setUserFormClose">取 消</el-button>
        <el-button type="primary" @click="confimUserForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户信息 -->
    <el-dialog title="编辑用户信息" :visible.sync="EditdialogVisible" width="50%">
      <el-form
        :model="EditruleForm"
        :rules="addUserFormRules"
        ref="EditruleForm"
        label-width="100px"
      >
        <el-form-item label="用户名">
          <el-input disabled v-model="EditruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="EditruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="EditruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditruleFormClose">取 消</el-button>
        <!-- 提交编辑的用户信息 -->
        <el-button type="primary" @click="putUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog @close="CloseRights" title="分配角色" :visible.sync="RightsdialogVisible" width="50%">
      <el-form ref="form" label-width="80px">
        <el-form-item label="当前用户">
          <el-input disabled v-model="userInfo.username"></el-input>
        </el-form-item>
        <el-form-item label="当前角色">
          <el-input disabled v-model="userInfo.role_name"></el-input>
        </el-form-item>
        <!-- 分配角色下拉框 -->
        <el-form-item label="选择角色">
          <el-select v-model="defaultValue" placeholder="请选择分配角色">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="RightsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setUserEoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// import moment from 'moment'
import { UserList, ChangeUserInfo, AddUser, EditUserInfo, EditUserInfoPost, RemoveUser, UserRoles, PostUser } from '@/api/api.js'
export default {
  name: 'BackShopUsers',

  data () {
    // 添加邮箱正则
    var mailRule = (rule, val, cb) => {
      // 邮箱正则验证
      const mail = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      // 通过
      if (mail.test(val)) {
        return cb()
      };
      // 不通过
      cb(new Error('邮箱格式错误！'))
    };
    // 添加手机号正则
    var MobileRule = (rule, val, cb) => {
      // 邮箱正则验证
      const mobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      // 通过
      if (mobile.test(val)) {
        return cb()
      };
      // 不通过
      cb(new Error('手机号格式错误！'))
    };
    return {
      // 请求参数
      queryInfo: {
        query: '',
        // 页数
        pagenum: 1,
        // 获取长度
        pagesize: 2
      },
      // 用户列表
      userList: [],
      // 总数
      totol: 5,
      // 新增用户框显示隐藏
      dialogVisible: false,
      // 添加用户表单
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户正则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: mailRule, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { validator: MobileRule, trigger: 'blur' }
        ]

      },
      // 编辑用户信息显示隐藏
      EditdialogVisible: false,
      // 编辑用户信息
      EditruleForm: {},
      // 分配角色Show
      RightsdialogVisible: false,
      // 当前列的角色信息
      userInfo: {},
      // 下拉菜单选择的角色信息
      rolesList: [],
      // 默认展示的当前角色
      defaultValue: ''
    };
  },
  created () {
    // 请求用户列表数据
    this.getUserList();

  },
  methods: {
    // 获取用户数据
    async getUserList () {
      const { data: res } = await UserList({ params: this.queryInfo })
      if (res.meta.status != 200) return this.$message.error('获取用户列表失败');
      this.userList = res.data.users;
      this.totol = res.data.total;
    },
    // 显示请求显示列表数据总数
    handleSizeChange (pagesize) {
      // console.log(newPage);
      this.queryInfo.pagesize = pagesize;
      // 从新请求数据
      this.getUserList()
    },
    // 显示请求几页数据
    handleCurrentChange (newPage) {
      // console.log(newPage);
      this.queryInfo.pagenum = newPage;
      // 从新请求数据
      this.getUserList()
    },
    // 修改用户数据
    async ChangeSwitch (userInfo) {
      const { data: res } = await ChangeUserInfo(userInfo.id, userInfo.mg_state)
      if (res.meta.status != 200) {
        userInfo.mg_state = !userInfo.mg_state;
        return this.$message.error('修改用户状态失败！')
      }
      this.$message.success('修改用户状态成功')

    },
    // 取消添加用户清除表单校验样式
    setUserFormClose () {
      this.$refs.addUserForm.resetFields();
      this.dialogVisible = false;
    },
    // 确认表单预校验
    confimUserForm () {
      this.$refs.addUserForm.validate(async validate => {
        //  格式预校验
        if (!validate) return;
        const { data: res } = await AddUser(this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error('用户添加失败!')
        this.$message.success('用户添加成功!')
        // 关闭添加用户框
        this.dialogVisible = false;
        // 从新获取数据
      })
    },
    // 编辑设置用户信息
    async editChangeVal (id) {
      const { data: res } = await EditUserInfo(id)
      if (res.meta.status !== 200) return this.$message.error('获取用户信息失败');
      // 显示编辑用户信息栏
      this.EditdialogVisible = true;
      this.EditruleForm = res.data;
    },
    // 取消用户编辑取消校验提示
    EditruleFormClose () {
      this.EditdialogVisible = false;
      this.$refs.EditruleForm.resetFields()
    },
    // 修改用户信息提交数据
    putUserInfo () {
      this.$refs.EditruleForm.validate(async validate => {
        if (!validate) return;
        const { data: res } = await EditUserInfoPost(this.EditruleForm.id, { email: this.EditruleForm.email, mobile: this.EditruleForm.mobile })
        if (res.meta.status !== 200) return this.$message.error('编辑用户信息失败');
        this.$message.success('更新用户信息成功！')
        // 关闭编辑信息显示框
        this.EditdialogVisible = false;
        // 编辑成功后从新获取数据
        this.getUserList()
      })
    },
    // 删除用户信息 
    async removeInfo (id) {
      let messageBoxResult = await this.$messageBox('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);
      if (messageBoxResult !== 'confirm') return this.$message.info('删除用户失败！');
      const { data: res } = await RemoveUser(id);
      if (res.meta.status !== 200) return this.$message.error('删除用户失败！')
      this.$message.success('删除用户成功！');
      // 删除成功从新获取数据
      this.getUserList()
    },
    // 分配角色
    async SetUserRights (row) {
      this.RightsdialogVisible = true
      // 点击显示当前这一个的角色信息
      this.userInfo = row;
      // 请求角色信息
      const { data: res } = await UserRoles()
      if (res.meta.status !== 200) return this.$message.error('请求角色信息失败！')
      // 赋值角色列表信息
      this.rolesList = res.data
    },
    // 提交角色
    async setUserEoles () {
      // 判断select是否被选
      if (!this.defaultValue) return this.$message.error('请选择角色信息！');
      const { data: res } = await PostUser(this.userInfo.id, { rid: this.defaultValue });
      if (res.meta.status == 400) return this.$message.error(res.meta.msg)
      if (res.meta.status !== 200) return this.$message.error('更新角色信息失败！');
      this.$message.success('设置角色信息成功！')
      // 同时从新获取数据
      this.getUserList();
      this.RightsdialogVisible = false;
    },
    // 清除分配角色对话框
    CloseRights () {
      // 关闭对话框清除默认
      this.defaultValue = '';
      this.userInfo = []
    }
  },
};
</script>

<style lang="less" scoped>
.el-select {
  width: 100%;
}
</style>